package com.java.digitalsignagesystem.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.digitalsignagesystem.entity.LoginVo;
import com.java.digitalsignagesystem.entity.User;
import com.java.digitalsignagesystem.entity.UserLogin;
import com.java.digitalsignagesystem.mapper.UserMapper;
import com.java.digitalsignagesystem.service.UserService;
import com.java.digitalsignagesystem.utils.Aes;
import com.java.digitalsignagesystem.utils.RedisUtil;
import com.java.digitalsignagesystem.utils.UKeyKit;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-08-30 15:49:30
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{


    @Value("${vpc.ip}")
    private String vpcIp;

    @Value("${vpc.port}")
    private String vpcPort;
    @Autowired
    RedisUtil redisUtil;
    @Resource
    private UserMapper userMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        return this.userMapper.queryById(id);
    }

    /**

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userMapper.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userMapper.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userMapper.deleteById(id) > 0;
    }

    @Override
    public String selectDeptByUser(String user) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user);
        User user1 = userMapper.selectById(user);
        String dept = user1.getDept();
        return dept;
    }

    @Override
    public String getUserInfo(String token) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://10.1.229.72/dataway-hinglo/jnxm/aio/getUserInfo?token="+token)
                .get()
                .addHeader("content-type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User getByUserName(String username) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getDept,username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public String login(LoginVo loginVo) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://"+vpcIp+":"+vpcPort+"/service/api/zp/dljk?user="+loginVo.getUser()+"&password="+loginVo.getPassword())
                .get()
                .addHeader("content-type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User getByAccount(String account) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,account);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, String> ukLogin()  {
        String randId = RandomUtil.randomString(16);
        String random = UKeyKit.genRandom(randId);
        String certByAppId = UKeyKit.getCertByAppId(randId);
        String sign = UKeyKit.sign(random, randId);
        Map<String, String> map = new HashMap<>();
        map.put("random",random);
        map.put("certByAppId",certByAppId);
        map.put("sign",sign);
        System.out.println(map);
        return map;
    }

    @Override
    public String verifyDataSign(String signValue, String random, String certByAppId) {
        String randId = RandomUtil.randomString(16);
        return UKeyKit.verifyDataSign(signValue, random, certByAppId, randId);
    }


    @Override
    public String sendMessage(String phone) {
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<6;i++){
            int random = RandomUtil.randomInt(0, 9);
            stringBuilder.append(random);
        }
        String code = redisUtil.getCacheObject("code"+phone);
        if(ObjectUtil.isEmpty(code)){
            code = stringBuilder.toString();
            redisUtil.setCacheObject("code"+phone,code,10, TimeUnit.MINUTES);
        }
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("code", code)
                .add("phone", phone)
                .add("platform","体征平台")
                .build();
        Request request = new Request.Builder()
                //打包
                .url("http://10.1.229.72/dataway-hinglo/zhrc/v1/sm/send")
                //测试
                //.url("http://10.1.213.82/api-generate/dataway-hinglo/zhrc/v1/sm/send")
                .post(formBody)
                .addHeader("content-type", "application/json")
                .addHeader("auth-password","60cdbfef1e2a8a18cfa627c16e5833c4")
                .build();

        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String verifyLogin(UserLogin userLogin) {
        String password = Aes.aesDecrypt(userLogin.getPassword());
        userLogin.setPassword(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userLogin.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtil.isEmpty(user)){
            return "[]";
        }
        String encrypt = Aes.aesDecrypt(user.getPassword());
        if(!encrypt.equals(password)){
            return "[]";
        }
        return user.toString();

        /*String path = "http://"+vpcIp+":"+vpcPort+"/service/api/zp/dljk?user="+userLogin.getUsername()+"&password="+userLogin.getPassword();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(path)
                .get()
                .addHeader("content-type", "application/json")
                .build();
        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
    }


}
